/**
Name: Nishant Kumar
Andrew Id: nkumar1
Course: 15-637
Date: 3/12/2012
 **/

package edu.cmu.fithub.actions;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.hibernate.exception.DataException;

import edu.cmu.fithub.controller.Action;
import edu.cmu.fithub.db.DBHelper;
import edu.cmu.fithub.db.bean.User;

public class ImageAction extends Action {

	public ImageAction() {
	}

	public String getName() {
		return "image.do";
	}

	public String perform(HttpServletRequest request) {

		List<String> errors = new ArrayList<String>();
		request.setAttribute("errors", errors);
		String id = request.getParameter("userId");
		try {
			Session dbSession = DBHelper.getSessionFactory().openSession();
			List<User> userList = dbSession.createCriteria(User.class)
					.add(Restrictions.eq("userId", Integer.parseInt(id)))
					.list();

			if (userList.size() != 0) {
				// if user did not upload a picture return default image
				if (userList.get(0).getImage() == null) {
					return "images/users/thumb/pinocchio.jpg";
				} else {
					request.setAttribute("userImage", userList.get(0));
				}
			} else {
				// invalid userID. return default image
				return "images/users/thumb/pinocchio.jpg";
			}
		} catch (NumberFormatException e) {
			errors.add(e.toString());
			return "images/users/thumb/pinocchio.jpg";
		} catch (DataException e) {
			errors.add(e.toString());
			return "images/users/thumb/pinocchio.jpg";
		}
		return "image";
	}
}
